package BehaviorModel.iterorModel;

import java.util.Iterator;

public class ComputerReserveCollege implements College {
    private Department[] departments;
    private int numOfDepartment = 0;

    private Iterator iterator;
    public ComputerReserveCollege(Department[] departments) {
        this.departments = departments;
        this.numOfDepartment = departments.length-1;
    }

    @Override
    public String getName() {
        return "计算机院系逆序";
    }

    @Override
    public void addDepartment(Department department) {
        Department[] targetDepartments = new Department[this.departments.length + 1];
        System.arraycopy(this.departments, 0, targetDepartments, 0, this.departments.length);
        targetDepartments[++this.numOfDepartment] = department;
        this.departments = targetDepartments;
        createIterator();
    }

    @Override
    public void removeDepartment(Department department) {
        for (int index = 0; index < departments.length; index++) {
            if (department.equals(departments[index])){
                swapAndRemoveItem(index);
            }
        }
    }
    private void swapAndRemoveItem(int index) {
        if (index!= numOfDepartment){
            Department temp = departments[index];
            departments[index] = departments[numOfDepartment];
            departments[numOfDepartment] = temp;
        }
        departments[numOfDepartment] = null;
        numOfDepartment--;
    }
    @Override
    public Iterator createIterator() {
        if (null == iterator){
            return new ComputerReserveIteror(this.departments);
        }else {
            ComputerReserveIteror iteror =(ComputerReserveIteror)this.iterator;
            iteror.setDepartments(departments);
        }
        return this.iterator;
    }
}
